package com.mj.mybatis;

import com.mj.domain.UserDO;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 马洁
 * @date 2020/9/18 - 10:54
 */
public class MySqlSessionFactoryBuilder {
    static SqlSessionFactoryBuilder sqlSessionFactoryBuilder;

    static {
        sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    }

    public MySqlSessionFactoryBuilder() {
    }

    public MySqlSessionFactory build(InputStream inputStream) {
        DataSource dataSource = getDataSource(inputStream);
        // 解析xml，添加映射
        Map<String, SqlBean> mapper = getMapper();

        MySqlSessionFactory mySqlSessionFactory = new MySqlSessionFactoryImpl(dataSource, mapper);

        return mySqlSessionFactory;
    }

    private DataSource getDataSource(InputStream inputStream) {
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        Configuration configuration = sqlSessionFactory.getConfiguration();
        Environment environment = configuration.getEnvironment();
        DataSource dataSource = environment.getDataSource();

        return dataSource;
    }

    private Map<String, SqlBean> getMapper() {
        Map<String, SqlBean> mapper = new HashMap<>();
        mapper.put("com.mj.dao.IUserMapper.findAll",
                new SqlBean("select * from user", UserDO.class));

        return mapper;
    }
}
